package com.shopping.servlet.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.shopping.dao.OrderDao;
import com.shopping.dao.UserDao;
import com.shopping.dao.impl.UserDaoImpl;
import com.shopping.pojo.User;
import com.shopping.service.OrderService;
import com.shopping.service.UserService;
import com.shopping.service.impl.OrderServiceImpl;
import com.shopping.service.impl.UserServiceImpl;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public LoginServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().println("Get");
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");

		// 输出
		PrintWriter out = response.getWriter();
		
		// 获取参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username + "\n" + password);
		
		
		// 登录验证
		HttpSession session =  request.getSession();
		UserService service = new UserServiceImpl();
		boolean b = service.login(username, password);
		if(b) {
			User user = service.getUser(username, password);
			session.setAttribute("username", user.getUsername());
			session.setAttribute("user", user);

			UserService us = new UserServiceImpl();
			OrderService os = new OrderServiceImpl();
			
			session.setAttribute("users_count", us.getTotalData());
			session.setAttribute("order_count", os.getTotalData());
			response.sendRedirect("/shoppingmall/index.jsp");
//			request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
		}else {
			out.println("<p>用户名或密码错误</p>");
			response.setHeader("refresh", "1;url=/shoppingmall/login.jsp");
//			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}
	}

}
